import { addToast } from '@/components/common/Toast/toast.module'

const ua = navigator.userAgent.toLowerCase()

const isJdApp = function () {
	return !!(
		ua.indexOf('jdapp') > -1 &&
		(window.AndroidNavi || window.MobileNavi || window._is_jdsh_wkwebview)
	)
}

const isJrApp = function () {
	return ua.indexOf('jdjr') > -1 || ua.indexOf('android-async-http') > -1 || false
}

const setCookie = function (name, value, domain) {
	const Days = 30
	const exp = new Date()
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
	document.cookie = `${name}=${escape(value)};expires=${exp.toGMTString()}; domain=${
		domain.domain
	}`
}

// 读取cookies
const getCookie = function (name) {
	const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`)
	const arr = document.cookie.match(reg)
	if (arr) return unescape(arr[2])
	return null
}

function obj2getp(data) {
	let ret = ''
	const cache = []
	if (typeof data !== 'object' || data === null) {
		return ret
	}
	Object.keys(data).forEach((k) => {
		cache.push(`${k}=${data[k]}`)
	})
	ret = cache.join('&')
	return ret
}

function isH5Login() {
	const zin = getCookie('zin')
	const pwdtId = getCookie('pwdt_id')
	const pin = getCookie('pin')
	const jdpin = getCookie('jdpin')
	const pt_key = getCookie('pt_key')
	if (zin || pwdtId || pin || jdpin || pt_key) {
		return true
	}
	return false
}

function gotoLogin() {
	setCookie('goToLogin', 'true', { domain: 'jd.com' })
	window.location.href = `//plogin.m.jd.com/user/login.action?appid=375&returnurl=${encodeURIComponent(
		window.location.href
	)}`
}

export function toSettleAccounts(param) {
	// app专享在 非app环境中下单处理  ---在前面进行判断
	// if (!(isJdApp() || isJrApp())) {
	// addToast('请前往app下单')
	// return
	// }

	if (!isH5Login()) {
		return gotoLogin()
	}

	const data = {
		projectId: param.projectId,
		redoundId: param.redoundId,
		from: '',
		orderfrom: '',
		supportNum: param.supnum,
		// TODO  二期增加颜色尺寸后传参
		redoundSpec: '',
		eid: '',
		fp: '',
		sid: '',
		token: '',
	}
	// 风控天盾系统接入
	let risk_jd = ''
	try {
		risk_jd = getJdEid()
		data.eid = risk_jd.eid
		data.fp = risk_jd.fp
		data.sid = risk_jd.sid
		data.token = risk_jd.token
	} catch (e) {}
	let orderUrl = '//zt.m.jd.com/funding/support_project.action'
	orderUrl = `${orderUrl}?${obj2getp(data)}`
	console.log(JSON.stringify(orderUrl))
	window.location.href = orderUrl
}
